package branch_access;

import java.io.IOException;
import mware_lib.communication.ObjectStream;
import mware_lib.communication.Server;
import mware_lib.exceptions.IllegalMessageException;
import mware_lib.messages.ReqManMsg;

public class ManagerSkeleton implements Runnable {

	private volatile boolean running;
	private Thread thread;

	
	private Server server;
	private Manager manager;
	private String nsHost;
    private int nsPort;


	public ManagerSkeleton(int managerPort, Manager manager, String nsHost, int nsPort) throws IOException {
		this.running = true;
		this.thread = new Thread(this);
		this.server = new Server(managerPort);
		this.manager = manager;
		this.nsHost = nsHost;
        this.nsPort = nsPort;
	}

	@Override
	public void run() {
		while (this.running) {
			try {
				this.server.accept();
				ObjectStream os = this.server.getObjectStream();
				Object rcvdObj;
				try {
					rcvdObj = os.receive();
					if (!(rcvdObj instanceof ReqManMsg)) {
						os.send(new IllegalMessageException(rcvdObj.getClass()
								.toString()));
					}else{
						doReq((ReqManMsg) rcvdObj, os);
					}
				} catch (ClassNotFoundException e) {
					os.send(new ClassNotFoundException(e.getMessage()));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void stop(){
		this.running = false;
	}
	
	public void start(){
		this.thread.start();
	}

	private void doReq(ReqManMsg rcvdObj, ObjectStream os) {
		ManagerWorker worker = new ManagerWorker(this.manager, rcvdObj, os, nsHost, nsPort);
		Thread thread = new Thread(worker);
        thread.start();

	}

}
